from scrapy.command import ScrapyCommand
from ..models import db
from ..models import Illustration, Artist, DailyRank, Page


class Command(ScrapyCommand):

    requires_project = True

    def syntax(self):
        return 'ceatedb'

    def short_desc(self):
        return 'Create database descripted in settings.py'

    def add_options(self, parser):
        ScrapyCommand.add_options(self, parser)

    def process_options(self, args, opts):
        ScrapyCommand.process_options(self, args, opts)

    def run(self, args, opts):
        uri = self.settings['DATABASE_URI']
        db.initialize_from_uri(uri, check=False)

        tables = [Illustration, Page, Artist, DailyRank]

        try:
            db.create_tables(tables)
        except:
            raise RuntimeError("Couldn't create database. If you are using MySQL, "
                               "please create the database in MySQL first.")